package com.EmployeeButler.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.EmployeeButler.entity.User;
import com.EmployeeButler.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 作者
 * @since 2024-06-11
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @GetMapping("/add")
    public String userAdd() {
        return "admin/user_add";
    }

    @GetMapping("/{id}")
    public String userUpdate(@PathVariable String id,Model model) {
        User user = userService.getById(id);
        model.addAttribute("user", user);
        return "admin/user_update";
    }

    /**
     * 新增与修改用户
     * @param user
     * @return {@link SaResult }
     */
    @PostMapping
    @ResponseBody
    public SaResult save(User user) {
        if (user.getId() == null) {
//            增
            userService.save(user);
        } else {
//            修改
            userService.updateById(user);
        }
        return SaResult.ok();
    }



    /**
     * 移除用户
     * @param id
     * @return {@link SaResult }
     */
    @GetMapping("/remove/{id}")
    @ResponseBody
    public SaResult remove(@PathVariable String id) {
        userService.removeById(Integer.parseInt(id));
        return SaResult.ok();
    }

    @GetMapping("/search")
    public String search(@RequestParam(required = false) String keyword, Model model) {
        // 定义用户列表
        List<User> users;

        // 检查关键字是否为空
        if (keyword == null || keyword.isEmpty()) {
            users = userService.list();
        } else {
            users = userService.list(new QueryWrapper<User>()
                    .like("name", keyword));
        }
        // 将用户列表添加到模型中
        model.addAttribute("users", users);
        return "admin/users";
    }



    @PostMapping("/login")
    @ResponseBody
    public SaResult login(User user) {
        User foundUser = userService.getOne(new QueryWrapper<User>()
                .eq("username", user.getUsername()));
        if (foundUser == null) {
            return SaResult.error("账号不存在！");
        }
        if (foundUser.getPassword().equals(user.getPassword())) {
            StpUtil.login(foundUser.getId());
            StpUtil.getSession().set("role", foundUser.getRole());
            return SaResult.ok();
        } else {
            return SaResult.error("密码错误！");
        }
    }

    @PostMapping("/register")
    @ResponseBody
    public SaResult register(User user) {
        userService.save(user);
        return SaResult.ok();
    }


}
